<?php
/**
 * Created by PhpStorm.
 * Author: ExtraXue
 * Date: 2018/5/7
 * Description:
 */

//把图片转换成base64进行存储
function base64EncodeImage($image_file)
{
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}

require_once('pdo.php');
$picBase64 = base64EncodeImage($_FILES["breakingNewsPic"]["tmp_name"]);

date_default_timezone_set('PRC');
$nowDate = date('Y-m-d-H-i-s');
$newsContent = $_POST['field2'];
$newsTitle = $_POST['newsTitle'];
$newsAuthor = $_POST['newsAuthor'];
$newsType = $_POST['newsType'];
$newLocation = $_SERVER['DOCUMENT_ROOT'];


if (($newsContent <> '<p><br></p>') && ($newsTitle <> '') && $picBase64 &&
    ($_FILES["breakingNewsPic"]["type"]=='image/jpeg'||$_FILES["breakingNewsPic"]["type"]=='image/png'))
{
    if (move_uploaded_file($_FILES["breakingNewsPic"]["tmp_name"], "$newLocation\\graduationProject\\code\\temp\\" . $nowDate)) {
        $sql = "insert into news_info (news_title, news_content, create_time,news_author,news_type,change_time,is_breakingnews,pic_location)
values ('{$newsTitle}','{$newsContent}','{$nowDate}','{$newsAuthor}','{$newsType}','{$nowDate}','1','$newLocation/graduationProject/code/temp/$nowDate')";
        $pdo->exec($sql);
        echo "<script>alert('发布头条成功！');history.back()</script>";
    } else {
        echo "<script>alert('转移临时文件失败！');history.back()</script>";
    }

} else {
    echo "<script>alert('发布失败，请填写新闻标题和新闻正文内容或补充头条封面图片或是因为上传的不是.png或.jpeg图片！');history.back();</script>";
}
?>